//
//  GuideBookViewController.m
//  FourthProject
//
//  Created by mac on 16/5/26.
//  Copyright © 2016年 cry. All rights reserved.
//

#import "GuideBookViewController.h"
#import "CommonView.h"
#import "BookObject.h"

@interface GuideBookViewController ()<UIScrollViewDelegate>
{
    NSMutableArray              *_catalogueArray;
    NSMutableArray              *_moveViewLengthArray;
    NSMutableArray              *_countryArray;
    
    UIButton                    *_lastClickedButton;
    
    
}
@end

@implementation GuideBookViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self getData];

    
    
    
 
}

- (void)getData {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSDictionary *dic1 = @{@"client_id":@"qyer_android",@"client_secret":@"9fcaae8aefc4f9ac4915",@"v":@"1",@"track_deviceid":@"869070029694844",@"track_app_version":@"6.9.0",@"track_app_channel":@"xiaomi",@"track_device_info":@"lte26007",@"track_os":@"Android4.4.4",@"app_installtime":@"1463542775388",@"track_user_id":@"7911957",@"lat":@"24.548208",@"lon":@"118.1244"};
    
    [manager POST:@"http://open.qyer.com/qyer/guide/category_list" parameters:dic1 progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        _catalogueArray = [NSMutableArray arrayWithArray:responseObject[@"data"]];
        
        [self getAllBook];
        
        [self layoutScroll];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"!!!!!%@",error);
    }];
    
}

- (void)getAllBook {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:@{@"client_id":@"qyer_android",@"client_secret":@"9fcaae8aefc4f9ac4915",@"v":@"1",@"track_deviceid":@"869070029694844",@"track_app_version":@"6.9.0",@"track_app_channel":@"xiaomi",@"track_device_info":@"lte26007",@"track_os":@"Android4.4.4",@"app_installtime":@"1463542775388",@"track_user_id":@"7911957",@"lat":@"24.548208",@"lon":@"118.1244"}];
    
    for (int i = 0; i < _catalogueArray.count; i++) {

        [dic setObject:_catalogueArray[i][@"id"] forKey:@"id"];
        
        [manager POST:@"http://open.qyer.com/qyer/guide/channel_list" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //NSLog(@"---------%@",responseObject);
            
            CommonView *CV = [[CommonView alloc] initWithFrame:CGRectMake(WIDTH * i, 0, WIDTH, HEIGHT - 66 - 40)];

            NSMutableArray *tempArr = [[NSMutableArray alloc] initWithCapacity:0];
            
            _countryArray = [NSMutableArray arrayWithArray:responseObject[@"data"]];
            
            for (int j = 0; j < _countryArray.count; j++) {
             
                NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:_countryArray[j]];
                
                NSMutableArray *aaa = [BookObject mj_objectArrayWithKeyValuesArray:tempDic[@"guides"]];
                
                [tempDic setValue:aaa forKey:@"guides"];
                
                //NSLog(@"^^^^^^%@",tempDic);
                [tempArr addObject:tempDic];
                //NSLog(@"+++++++++++%ld",tempArr.count);
            }

            
            CV.countryArray = tempArr;
            [self.contentScroll addSubview:CV];
            //NSLog(@"-----%@",CV.countryArray);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"!!!!!!%@",error);
        }];
        
    }
    
}

- (void)layoutScroll {
    
    self.moveView = [[UIView alloc] init];
    self.moveView.frame = CGRectMake(0, 35, 34 * 3 / 2, 5);
    self.moveView.backgroundColor = [UIColor greenColor];
    [self.headerScroll addSubview:self.moveView];

    NSMutableArray *btnNameArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    float length = 0;
    
    for (int i = 0; i < _catalogueArray.count; i++) {
        [btnNameArray addObject:_catalogueArray[i][@"cnname"]];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        float w = [self getWidth:btnNameArray[i]] * 3 / 2;
        btn.frame = CGRectMake(length, 0, w, 35);
        length += w;
        btn.tag = 100 + i;
        [btn setTitle:btnNameArray[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.headerScroll addSubview:btn];
    }
    self.headerScroll.contentSize = CGSizeMake(length, 40);
    
    self.contentScroll.contentSize = CGSizeMake(_catalogueArray.count * WIDTH,  HEIGHT - 66 -40);
}
#pragma mark -----scroll
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    int m = scrollView.contentOffset.x / WIDTH;
    
    UIButton *button = [self.view viewWithTag:m + 100];
    
    [UIView animateWithDuration:0.5 animations:^{
        if (button != _lastClickedButton) {
            //待优化
            self.headerScroll.contentOffset = CGPointMake(40 * (button.tag - 100), self.headerScroll.contentOffset.y);

            self.moveView.frame = CGRectMake(button.frame.origin.x, self.moveView.frame.origin.y, button.frame.size.width, self.moveView.frame.size.height);
            
            [button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
            [_lastClickedButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }];
    _lastClickedButton = button;
}

- (void)buttonClick:(id)sender {
    UIButton *button = (UIButton *)sender;
    
    [UIView animateWithDuration:0.5 animations:^{
      
         self.contentScroll.contentOffset = CGPointMake((button.tag - 100) * WIDTH, self.contentScroll.contentOffset.y);
        
        if (button != _lastClickedButton) {
            //待优化
            self.headerScroll.contentOffset = CGPointMake(40 * (button.tag - 100), self.headerScroll.contentOffset.y);

            self.moveView.frame = CGRectMake(button.frame.origin.x, self.moveView.frame.origin.y, button.frame.size.width, self.moveView.frame.size.height);
            
            [button setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
            [_lastClickedButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }];
    _lastClickedButton = button;
}

- (float)getWidth:(NSString *)string {
    
    CGRect rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
    return rect.size.width;
}

- (IBAction)backButtonClick:(id)sender {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}



@end
